import cookie from '@/utils/cookie'
import { setOpenId, getOpenId } from '@/utils/auth'
import axios from 'axios'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import service from '@/utils/request'

//APPID: import.meta.env.VUE_APP_WX_APPID
const APPID = 'wxd6c52d789ba647a3'
const WX_AUTH_URL =
	'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
	APPID +
	'&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=connect_redirect=1#wechat_redirect'
/**
 * 微信授权
 */
export default function wxAuth() {
	return new Promise((resolve, reject) => {
		let openid = cookie.get('openid')
		if (openid) {
			console.log('用户已授权openId为：===>>' + openid)
			resolve(openid)
			return
		}
		//第一步：用户同意授权，获取code
		let code = getUrlParam('code')
		console.log('URL 中的CODE，跳转到取CODE授权页面' + code)
		if (!code) {
			//未经过微信授权
			console.log('没有CODE，跳转到取CODE授权页面')
			let currentUrl = encodeURIComponent(window.location.href)
			window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl))
		} else {
			service
				.post('/wxapi/wxAuth/codeToUserInfo', {
					code: code
				})
				.then((res) => {
					if (res.code == 200) {
						console.log('微信授权完成,获取到openid:' + res.data)
						showToast('微信授权完成,获取到用户信息为:' + res.data)

						setOpenId(res.data) // localstorage 存储User info DATA
						openid = cookie.get('openid')
						// 假设返回的response.data是一个WxUser对象
						const WxUser = res.data
						// 转化为Vue3的Reactive对象
						const wxUserInfo = reactive({ ...WxUser })

						// 使用state
						console.log('有户数据：' + wxUserInfo)
						resolve(wxUserInfo.openid)
					} else {
						console.log('换取openid失败')
					}
				})
		}
	})
}

// 获取当前页面url中的参数KEY对应的Value值。
function getUrlParam(key) {
	// 获取当前页面url中的参数
	var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
	var result = window.location.search.slice(1).match(reg)
	return result ? decodeURIComponent(result[2]) : ''
}
